const api = require('../../../ws_micro_shop/utils/api.js');
const app = getApp();

let is_no_more = false;
let is_loading = false;
let p = 2;

Page({
  data: {
    order_list: [],
    show_no_data_tip: false,
    hide: 1,
    robots: [],
    robot_id: '',
    showRobotPicker: false,
    isShow: false,
    goodstype: '',
    orderid: 0,
    abnorData: {
      imgSrc: '/common/static/images/abnor-10.png',
      text: '还没有相关订单哦',
    },
    unit: '',
    savelist: [],
    isChangeModal: true,
    isShowModal: true,
    isTabShow: true,
    writeoffnum: '', // 核销数量
    isShowReasonModal: false,
    orderReason: '',
    toView: 'item-1',
    currVal: '',
    isLoading: false,
  },
  onLoad(options) {
    let that = this;
    let status = options.status;
    let type = options.type;
    if (options && options.shop_id) {
      app.ws_micro_shop_globalData.shopid = options.shop_id;
    }
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
      });
    });
    this.setData({
      status,
      type,
      toView: 'item' + status,
    });
    app.pageOnLoad(this);
    if (type === 'pt') {
      wx.setNavigationBarTitle({
        title: '拼团管理',
      });
    } else if (type === 'ms') {
      wx.setNavigationBarTitle({
        title: '秒杀管理',
      });
    } else if (type === 'yy') {
      wx.setNavigationBarTitle({
        title: '预约管理',
      });
    }
    is_no_more = false;
    is_loading = false;
    p = 2;
    app.ws_micro_shoplogin().then(res => {
      this.loadOrderList(this.data.type, this.data.status);
      this.loadExpressList();
    });
  },
  onShow() {
    if (this.data.type === 'pt') {
      this.getRobotList();
    }
  },
  onReachBottom() {
    let that = this;
    if (is_loading || is_no_more) {
      return;
    }
    is_loading = true;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.adminer.list,
      data: {
        type: that.data.type,
        status: that.data.status,
        page: p,
      },
      success: function(res) {
        wx.hideLoading();
        if (res.code === 0) {
          let order_list = that.data.order_list.concat(res.data.list);
          that.setData({
            order_list: order_list || [],
          });
          if (res.data.list.length === 0) {
            is_no_more = true;
            // wx.showToast({
            //   title: '没有更多数据了',
            //   icon: 'none',
            // });
          }
        }
        p++;
      },
      complete: function() {
        is_loading = false;
      },
    });
  },
  loadExpressList() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.adminer.expressList,
      success: function (res) {
        if (res.code === 0) {
          that.setData({
            expressList: res.data,
          });
        } else {
          wx.showToast({
            title: res.msg || '',
            icon: 'none',
          });
        }
      },
    });
  },
  loadOrderList(type, status, k = '') {
    let that = this;
    wx.showLoading({
      title: '正在加载',
      mask: true,
    });
    that.setData({
      isLoading: false,
    })
    app.ws_micro_shoprequest({
      url: api.adminer.list,
      data: {
        type: type,
        status: status,
        keywords: k
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            order_list: res.data.list || [],
            isLoading: true,
          });
        }
        that.setData({
          show_no_data_tip: that.data.order_list.length === 0,
        });
      },
      complete: function() {
        wx.hideLoading();
      },
    });
  },
  switchList(e) {
    wx.pageScrollTo({
      scrollTop: 0,
    });
    let data = e.currentTarget.dataset;
    this.setData({
      status: data.status,
      toView: 'item' + data.status,
    });
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.loadOrderList(this.data.type, data.status, this.data.currVal);
  },
  adminPay(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let idx = e.currentTarget.dataset.idx;
    let oldlist = that.data.order_list;
    wx.showModal({
      title: '操作提示',
      content: '是否确认帮助用户付款',
      success: function(res) {
        if (res.confirm) {
          app.ws_micro_shoprequest({
            url: api.adminer.pay,
            data: {
              order_id: id,
            },
            success: function(res) {
              if (res.code === 0) {
                oldlist.splice(idx, 1);
                that.setData({
                  order_list: oldlist,
                });
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                  success: res => {
                    setTimeout(function() {
                      that.refreshParent();
                    }, 1500);
                  },
                });
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                });
              }
            },
          });
        }
      },
    });
  },
  //改价
  changePrice(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    let idx = e.currentTarget.dataset.idx;
    let orderAmount = e.currentTarget.dataset.price;
    let isModal = that.data.isChangeModal;
    let oldlist = that.data.order_list;
    console.log(orderAmount);
    if (isModal) {
      that.setData({
        isChangeModal: false,
        orderId: id,
        orderIndex: idx,
        orderAmount: orderAmount,
      });
    }
  },
  send(e) {
    let dataset = e.currentTarget.dataset;
    this.setData({
      isShow: true,
      savelist: [],
      goodstype: dataset.gtype,
      orderid: dataset.id,
      currentIdx: Number(dataset.idx),
    });
    this.loadExpress();
  },
  afterSale(e) {
    let that = this;
    let oprtype = that.data.type;
    let data = e.currentTarget.dataset;
    let id = data.id;
    let _type = data.type;
    let action = data.action;
    let idx = data.idx;
    let oldlist = that.data.order_list;
    let url = '';
    if (oprtype === 'default') {
      url = api.adminer.revoke;
    } else if (oprtype === 'pt') {
      url = api.adminer.ptRevoke;
    } else if (oprtype === 'ms') {
      url = api.adminer.miaoshaRevoke;
    }
    wx.showModal({
      title: '操作提醒',
      content: '是否确定执行该操作？',
      success: function(res) {
        if (res.confirm) {
          app.ws_micro_shoprequest({
            url: url,
            data: {
              order_refund_id: id,
              type: _type,
              action: action,
            },
            method: 'POST',
            success: function(res) {
              if (res.code === 0) {
                oldlist.splice(idx, 1);
                that.setData({
                  order_list: oldlist,
                });
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                  success: res => {
                    setTimeout(function() {
                      that.refreshParent();
                    }, 1500);
                  },
                });
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                });
              }
            },
          });
        }
      },
    });
  },
  refundOpr(e) {
    let that = this;
    let data = e.currentTarget.dataset;
    this.setData({
      dataset: data,
    });
    if (Number(data.state) === 0) {
      this.setData({
        isShowReasonModal: true,
      });
      return;
    }
    wx.showModal({
      title: '操作提醒',
      content: '是否确定执行该操作？',
      success: function(res) {
        if (res.confirm) {
          that.sureOprClick();
        }
      },
    });
  },
  sureOprClick() {
    let that = this;
    let oprtype = that.data.type;
    let data = that.data.dataset;
    let orderId = data.id;
    let status = data.state;
    let idx = data.idx;
    let oldlist = that.data.order_list;
    let reason = that.data.orderReason;
    app.ws_micro_shoprequest({
      url: api.adminer.refund,
      data: {
        type: oprtype,
        id: orderId,
        status,
        reason,
      },
      method: 'GET',
      success: function(res) {
        if (res.code === 0) {
          oldlist.splice(idx, 1);
          that.setData({
            order_list: oldlist,
            orderReason: '',
            isShowReasonModal: '',
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
  },
  changeReasonCancel() {
    this.setData({
      isShowReasonModal: false,
    });
  },
  getChangeReason(e) {
    this.setData({
      orderReason: e.detail.value,
    });
  },
  refundMoney(e) {
    let that = this;
    let data = e.currentTarget.dataset;
    this.setData({
      dataset: data,
    });
    if (Number(data.state) === 0) {
      this.setData({
        isShowReasonModal: true,
      });
      return;
    }
    wx.showModal({
      title: '操作提醒',
      content: '是否确定执行该操作？',
      success: function(res) {
        if (res.confirm) {
          that.sureMoneyClick();
        }
      },
    });
  },
  sureMoneyClick() {
    let that = this;
    let data = that.data.dataset;
    let orderId = data.id;
    let status = data.state;
    let idx = data.idx;
    let oldlist = that.data.order_list;
    let reason = that.data.orderReason;
    app.ws_micro_shoprequest({
      url: api.adminer.bookrefund,
      data: {
        order_id: orderId,
        status,
        reason,
      },
      method: 'POST',
      success: function(res) {
        if (res.code === 0) {
          if (Number(status) === 0) {
            oldlist.splice(idx, 1);
          } else {
            oldlist[idx].is_refund = 1;
          }
          that.setData({
            order_list: oldlist,
            orderReason: '',
            isShowReasonModal: '',
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
  },
  refreshParent() {
    let pages = getCurrentPages();
    if (pages.length > 1) {
      let prePage = pages[pages.length - 2];
      prePage.onGetData();
    }
  },
  getRobotList() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.adminer.robotList,
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            robots: res.data,
          });
        }
      },
    });
  },
  showPicker(e) {
    let robots = this.data.robots;
    let pid = e.currentTarget.dataset.id;
    let gid = e.currentTarget.dataset.gid;
    if (robots && robots.length > 0) {
      this.setData({
        showRobotPicker: true,
        pid,
        goods_id: gid,
        robot_id: this.data.robots[0].id,
      });
    } else {
      wx.showModal({
        title: '提示',
        content: '暂无拼团机器人，请前往PC端后台添加',
      });
    }
  },
  hidePicker() {
    this.setData({
      showRobotPicker: false,
    });
  },
  adminAddRobot() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.adminer.addRobot,
      method: 'GET',
      data: {
        pid: that.data.pid,
        goods_id: that.data.goods_id,
        robot_id: that.data.robot_id,
      },
      success: function(res) {
        if (res.code === 0) {
          wx.showToast({
            title: res.msg ? res.msg : '',
            icon: 'none',
          });
          wx.redirectTo({
            url: '/' + that.route + '?type=pt&status=6',
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
    });
    this.setData({
      showRobotPicker: false,
    });
  },
  bindPickerChange(e) {
    let idx = e.detail.value[0];
    let robotId = this.data.robots[idx].id;
    this.setData({
      robot_id: robotId,
    });
  },
  writeOff() {
    wx.scanCode({
      success(res) {
        if (res.path) {
          app.util.navigateTo(res.path, { scene: res.result });
        }
      },
    });
  },
  showModel(e) {
    let that = this;
    let data = e.currentTarget.dataset;
    that.setData({
      data,
      totalnum: data.item.totalnum || 0,
      isTabShow: false,
      restnum: data.item.goods_list[0].num - (data.item.totalnum || 0),
    });
    if (data.item.verify === 0) {
      that.writeOffSelf(data);
    } else {
      that.setData({
        isShowModal: false,
      });
    }
  },
  writeOffSelf(obj) {
    let that = this;
    if (obj.item.verify === 1 && !this.data.writeoffnum) {
      wx.showToast({
        title: '请输入核销数量',
        icon: 'none',
        duration: 2000,
      });
      return;
    }
    app.ws_micro_shoprequest({
      url: api.adminer.clerk,
      method: 'GET',
      data: {
        order_id: obj.item.order_id,
        verify_num: obj.item.verify === 0 ? '' : this.data.writeoffnum,
        order_no: obj.item.order_no,
      },
      success: function(res) {
        if (res.code === 0) {
          that.loadOrderList(that.data.type, that.data.status, that.data.currVal);
          wx.showToast({
            title: '核销成功',
            icon: 'none',
            duration: 2000,
          });
        } else {
          wx.showToast({
            title: res.msg || '',
            icon: 'none',
            duration: 2000,
          });
        }
        that.setData({
          isShowModal: true,
          writeoffnum: '',
          isTabShow: true,
        });
      },
    });
  },
  loadExpress() {
    let that = this;
    let order_id = that.data.orderid;
    app.ws_micro_shoprequest({
      url: api.adminer.getexpresss,
      method: 'GET',
      data: {
        order_id,
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            savelist: res.data.list,
          });
        } else {
          wx.showToast({
            title: res.msg || '',
            icon: 'none',
          });
        }
      },
    });
  },
  changePriceCancel() {
    let that = this;
    let isModal = that.data.isChangeModal;
    if (!isModal) {
      that.setData({ isChangeModal: true });
    }
  },
  changePriceConfirm() {
    let that = this;
    let isModal = that.data.isChangeModal;
    let orderList = that.data.order_list;
    let originalPrice = that.data.orderAmount;
    let orderId = that.data.orderId;
    let orderIndex = that.data.orderIndex;
    let revisePrice = that.data.revisePrice
      ? that.data.revisePrice
      : originalPrice;
    this.setData({ isChangeModal: true });
    if (Number(originalPrice) !== Number(revisePrice)) {
      let orderType = Number(revisePrice) > Number(originalPrice) ? 1 : 2;
      let diffeAmount = Math.abs(Number(revisePrice) - Number(originalPrice));
      wx.showModal({
        title: '提示',
        content: '确认修改订单价格吗？',
        success(res) {
          if (res.confirm) {
            app.ws_micro_shoprequest({
              url: api.order.change_price,
              data: {
                order_id: orderId,
                type: orderType,
                price: diffeAmount,
              },
              method: 'GET',
              success: function(res) {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                });
                if (res.code === 0) {
                  //改变页面中订单的价格
                  if (orderList[orderIndex].order_id === orderId) {
                    orderList[orderIndex].pay_price = revisePrice;
                    that.setData({ order_list: orderList });
                  }
                }
              },
            });
          } else if (res.cancel) {
            //取消改价
          }
        },
      });
    }
  },
  getChangePrice(e) {
    let val = Number(e.detail.value).toFixed(2);
    this.setData({ revisePrice: val });
  },
  getChangeNum(e) {
    let val = e.detail.value.replace(/^(0+)|[^\d]+/g, '');
    this.setData({ writeoffnum: val });
  },
  changeNumCancel() {
    let that = this;
    let isModal = that.data.isShowModal;
    if (!isModal) {
      that.setData({
        isShowModal: true,
        isTabShow: true,
      });
    }
  },
  changeNumConfirm() {
    let data = this.data.data;
    this.writeOffSelf(data);
  },
  inputChange(e) {
    let val = e.detail.value;
    if (val.trim()) {
      this.setData({
        isEmpty: false,
      });
    } else {
      this.setData({
        isEmpty: true,
      });
    }
    this.setData({
      currVal: val,
    });
  },
  searchSure() {
    let keyword = this.data.currVal.trim();
    this.searchTxt(keyword);
  },
  searchTxt(keyword) {
    wx.pageScrollTo({
      scrollTop: 0,
    });
    let { type, status } = this.data;
    is_no_more = false;
    is_loading = false;
    p = 2;
    this.loadOrderList(type, status, keyword);
  },
});
